package repositorys

import (
	"encoding/gob"
	"fmt"
	"os"
	"vala/configs"
)

func Store(data []Site) {
	file, _ := os.OpenFile(configs.DATA_PATH, os.O_CREATE|os.O_RDWR, os.ModePerm)
	_ = gob.NewEncoder(file).Encode(data)
}

func Add(obj Site) {
	Store(append(Query(), obj))
}

func Delete(site Site) {
	Store(Filter(Query(), func(s Site) bool {
		return s.Name != site.Name
	}))
}

func Filter(stu []Site, f func(s Site) bool) []Site {
	var r []Site
	for _, s := range stu {
		if f(s) == true {
			r = append(r, s)
		}
	}
	return r
}

func Find(site Site) (Site, error) {
	result := Filter(Query(), func(s Site) bool {
		return s.Name == site.Name
	})
	if len(result) > 0 {
		return result[0], nil
	}
	return Site{}, fmt.Errorf("NOT FOUND!")
}

func Query() []Site {
	var data []Site
	file, _ := os.OpenFile(configs.DATA_PATH, os.O_RDWR, os.ModePerm)
	_ = gob.NewDecoder(file).Decode(&data)
	return data
}
